// hooks/useBookingForm.js
import { useState, useCallback, useEffect } from 'react';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { bookingService, roomService, authService } from '../../../services';
import { useMessage } from '../../../hooks';

export const useBookingForm = (booking) => {
  const navigate = useNavigate();
  const { showSuccess, showError } = useMessage();
  
  // 表单初始化逻辑
  const getInitialState = useCallback(() => ({
    title: '',
    description: '',
    roomId: '',
    id: '',
    start: dayjs().add(30, 'minute'),
    end: dayjs().add(1.5, 'hour'),
    ...(booking && {
      title: booking.title || '',
      description: booking.description || '',
      roomId: booking.roomId || '',
      id: booking.id || '',
      start: booking.start ? dayjs(booking.start) : dayjs().add(30, 'minute'),
      end: booking.end ? dayjs(booking.end) : dayjs().add(1.5, 'hour')
    })
  }), [booking]);

  // 状态管理
  const [formData, setFormData] = useState(getInitialState);
  const [rooms, setRooms] = useState([]);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  // 房间数据获取
  const fetchRooms = useCallback(async () => {
    try {
      setLoading(true);
      const response = await roomService.getRooms(0, 100);
      setRooms(response?.items || []);
      setFormData(getInitialState());
    } catch (err) {
      showError('Failed to load rooms');
    } finally {
      setLoading(false);
    }
  }, [getInitialState, showError]);

  // 表单验证
  const validateForm = useCallback(() => {
    const newErrors = {};
    if (!formData.title) newErrors.title = 'Title is required';
    if (!formData.roomId) newErrors.roomId = 'Room is required';
    if (!formData.start) newErrors.start = 'Start time is required';
    if (!formData.end) newErrors.end = 'End time is required';
    if (formData.start && formData.end && formData.start.isAfter(formData.end)) {
      newErrors.end = 'End time must be after start time';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData]);

  // 表单提交
  const onSaveBooking = useCallback(async (e) => {
    e?.preventDefault();
    if (!validateForm()) return;

    setLoading(true);
    const bookingData = {
      StartDate: formData.start,
      EndDate: formData.end,
      RoomId: formData.roomId,
      UserId: authService.getUser().userId,
      Title: formData.title,
      Description: formData.description,
    };

    try {
      await bookingService.createBooking(bookingData);
      showSuccess('Booking created successfully');
      navigate("/bookings");
    } catch (err) {
      showError(err?.message || 'Failed to create booking');
    } finally {
      setLoading(false);
    }
  }, [formData, validateForm, navigate, showSuccess, showError]);

  // 字段更新
  const onPropertyChange = useCallback((field) => (e) => {
    const value = e.target?.value ?? e;
    setFormData(prev => ({ ...prev, [field]: value }));
    setErrors(prev => ({ ...prev, [field]: '' }));
  }, []);

  useEffect(() => {
    fetchRooms();
  }, [fetchRooms]);

  return {
    formData,
    rooms,
    loading,
    errors,
    onSaveBooking,
    onPropertyChange
  };
};